package color.koitq.picker.ad;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.DislikeInfo;
import com.bytedance.sdk.openadsdk.FilterWord;
import com.bytedance.sdk.openadsdk.PersonalizationPrompt;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import color.koitq.picker.App;
import color.koitq.picker.R;


public class AdManager {

    private final String TAG = AdConfig.AD_LOG_TAG;

    private static AdManager adManager = null;

    private Activity activity;

    private AdManager() {
        mTTAdNative = TTAdManagerHolder.get().createAdNative(App.getContext());
    }

    public AdManager setActivity(Activity activity) {
        this.activity = activity;
        return this;
    }

    public static AdManager getInstance() {
        if (adManager == null) {
            adManager = new AdManager();
        }
        if (adManager.mTTAdNative == null) {
            adManager.mTTAdNative = TTAdManagerHolder.get().createAdNative(App.getContext());
        }
        return adManager;
    }

    public void destory() {
        fullScreenVideoAd = null;
        mTTAdNative = null;
        adManager = null;
    }

    private TTAdNative mTTAdNative;
    private TTFullScreenVideoAd fullScreenVideoAd;

    /**
     * 只弹一次视频广告
     * */
    public void showVideoAdOnce() {
        if (mTTAdNative == null || !AdConfig.isShowAd || AdConfig.adDisable) {
            adClose();
        } else {
            if (AdActivity.onlyOneVideo) {
                AlertDialog tip = new AlertDialog.Builder(activity)
                        .setTitle("提示")
                        .setMessage("观看广告可以解锁所有功能哦！")
                        .setIcon(R.mipmap.ic_launcher)
                        .setCancelable(false)
                        .setPositiveButton("观看广告", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                AdActivity.onlyOneVideo = false;
                                showFullVideoAd();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.cancel();
                            }
                        })
                        .create();
                tip.show();
            } else {
                adClose();
            }
        }
    }

    /**
     * 每次都弹视频广告（暴击模式）
     * */
    public void showVideoAdEveryTime() {
        if (mTTAdNative == null || !AdConfig.isShowAd || AdConfig.adDisable) {
            adClose();
        } else {
            showFullVideoAd();
        }
    }

    /**
     * 按照时间间隔弹视频广告
     * */
    public void showVideoAdInterval() {
        if (mTTAdNative == null || !AdConfig.isShowAd || AdConfig.adDisable) {
            adClose();
        } else {
            AlertDialog tip = new AlertDialog.Builder(activity)
                    .setTitle("提示")
                    .setMessage("观看广告可以解锁所有功能哦！")
                    .setIcon(R.mipmap.ic_launcher)
                    .setCancelable(false)
                    .setPositiveButton("观看广告", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            AdActivity.lastWatchVideo = System.currentTimeMillis();
                            showFullVideoAd();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.cancel();
                        }
                    })
                    .create();
            tip.show();
        }
    }

    private void showFullVideoAd() {
        if (fullScreenVideoAd == null) {
            loadFullVideoAd(true);
        } else {
            fullScreenVideoAd.setFullScreenVideoAdInteractionListener(new TTFullScreenVideoAd.FullScreenVideoAdInteractionListener() {

                @Override
                public void onAdShow() {
                    Log.d(TAG, "Callback --> FullVideoAd show");
                }

                @Override
                public void onAdVideoBarClick() {
                    Log.d(TAG, "Callback --> FullVideoAd bar click");
                }

                @Override
                public void onAdClose() {
                    Log.d(TAG, "Callback --> FullVideoAd close");
                    fullScreenVideoAd = null;
                    adClose();
                    loadFullVideoAd(false);
                }

                @Override
                public void onVideoComplete() {
                    Log.d(TAG, "Callback --> FullVideoAd complete");
                }

                @Override
                public void onSkippedVideo() {
                    Log.d(TAG, "Callback --> FullVideoAd skipped");

                }
            });
            fullScreenVideoAd.showFullScreenVideoAd(activity);
        }
    }

    public void loadFullVideoAd(boolean directShow) {
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(AdConfig.getVideoCodeId())
                .build();
        mTTAdNative.loadFullScreenVideoAd(adSlot, new TTAdNative.FullScreenVideoAdListener() {
            //请求广告失败
            @Override
            public void onError(int code, String message) {
                Log.i(TAG, "全屏视频广告，" + code + " : " + message);
                if (directShow) {
                    adClose();
                }
            }

            //广告物料加载完成的回调
            @Override
            public void onFullScreenVideoAdLoad(TTFullScreenVideoAd ad) {
                if (!directShow) {
                    fullScreenVideoAd = ad;
                } else {
                    ad.setFullScreenVideoAdInteractionListener(new TTFullScreenVideoAd.FullScreenVideoAdInteractionListener() {

                        @Override
                        public void onAdShow() {
                            Log.d(TAG, "Callback --> FullVideoAd show");
                        }

                        @Override
                        public void onAdVideoBarClick() {
                            Log.d(TAG, "Callback --> FullVideoAd bar click");
                        }

                        @Override
                        public void onAdClose() {
                            Log.d(TAG, "Callback --> FullVideoAd close");
                            adClose();
                            loadFullVideoAd(false);
                        }

                        @Override
                        public void onVideoComplete() {
                            Log.d(TAG, "Callback --> FullVideoAd complete");
                        }

                        @Override
                        public void onSkippedVideo() {
                            Log.d(TAG, "Callback --> FullVideoAd skipped");

                        }
                    });
                    ad.showFullScreenVideoAd(activity);
                }
            }

            //广告视频/图片加载完成的回调，接入方可以在这个回调后展示广告
            @Override
            public void onFullScreenVideoCached() {

            }

            @Override
            public void onFullScreenVideoCached(TTFullScreenVideoAd ttFullScreenVideoAd) {

            }
        });
    }

    /**
     * 加载插屏广告
     */
    @SuppressWarnings({"ALL", "SameParameterValue"})
    public void loadDialogAdNew() {
        if (mTTAdNative == null || !AdConfig.isShowAd || AdConfig.adDisable) {
            adDialogClose();
            return;
        }
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(AdConfig.getDialogCodeId())
                //模板广告需要设置期望个性化模板广告的大小,单位dp,激励视频场景，只要设置的值大于0即可
                .setExpressViewAcceptedSize(500, 500)
                .setSupportDeepLink(true)
                .setOrientation(TTAdConstant.VERTICAL)//必填参数，期望视频的播放方向：TTAdConstant.HORIZONTAL 或 TTAdConstant.VERTICAL
                .build();
        mTTAdNative.loadFullScreenVideoAd(adSlot, new TTAdNative.FullScreenVideoAdListener() {
            //请求广告失败
            @Override
            public void onError(int code, String message) {
                Log.i(TAG, "插屏广告，" + code + " : " + message);
            }

            //广告物料加载完成的回调
            @Override
            public void onFullScreenVideoAdLoad(TTFullScreenVideoAd ad) {
                ad.showFullScreenVideoAd(activity);
            }

            //广告视频/图片加载完成的回调，接入方可以在这个回调后展示广告
            @Override
            public void onFullScreenVideoCached() {

            }

            @Override
            public void onFullScreenVideoCached(TTFullScreenVideoAd ttFullScreenVideoAd) {

            }
        });
    }

    private void adClose() {
        EventBus.getDefault().post(new ADCloseEvent());
    }

    private void adDialogClose() {
        EventBus.getDefault().post(new ADDialogCloseEvent());
    }


    public void showBannerBottom(ViewGroup container) {
        if (!AdConfig.isShowAd || AdConfig.adDisable) {
            return;
        }
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(AdConfig.getBannerCodeId()) //广告位id
                .setSupportDeepLink(true)
                .setAdCount(3) //请求广告数量为1到3条
                .setExpressViewAcceptedSize(600, 90) //期望模板广告view的size,单位dp
                .build();
        mTTAdNative.loadBannerExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            //请求失败回调
            @Override
            public void onError(int code, String message) {
                Log.d(TAG, "showBannerBottom code==" + code + ", message = " + message);
            }

            //请求成功回调
            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                if (ads == null || ads.get(0) == null) {
                    return;
                }
                final TTNativeExpressAd ad = ads.get(0);
                ad.setSlideIntervalTime(3 * 1000);
                ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
                    @Override
                    public void onAdClicked(View view, int i) {

                    }

                    @Override
                    public void onAdShow(View view, int i) {

                    }

                    @Override
                    public void onRenderFail(View view, String s, int i) {

                    }

                    @Override
                    public void onRenderSuccess(View view, float v, float v1) {
                        if (container != null) {
                            container.removeAllViews();
                            container.addView(view);
                        }
                    }
                });

                final DislikeInfo dislikeInfo = ad.getDislikeInfo();
                if (dislikeInfo != null && dislikeInfo.getFilterWords() != null && !dislikeInfo.getFilterWords().isEmpty()) {
                    final DislikeDialog dislikeDialog = new DislikeDialog(activity, dislikeInfo);
                    dislikeDialog.setOnDislikeItemClick(new DislikeDialog.OnDislikeItemClick() {
                        @Override
                        public void onItemClick(FilterWord filterWord) {
                            //用户选择不喜欢原因后，移除广告展示
                            container.removeAllViews();
                        }
                    });
                    dislikeDialog.setOnPersonalizationPromptClick(new DislikeDialog.OnPersonalizationPromptClick() {
                        @Override
                        public void onClick(PersonalizationPrompt personalizationPrompt) {

                        }
                    });
                    ad.setDislikeDialog(dislikeDialog);
                }

                ad.render();
            }
        });
    }

    public void showBannerMiddle(ViewGroup container) {
        if (!AdConfig.isShowAd || AdConfig.adDisable) {
            return;
        }
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(AdConfig.getBannerCodeId_600x150()) //广告位id
                .setSupportDeepLink(true)
                .setAdCount(3) //请求广告数量为1到3条
                .setExpressViewAcceptedSize(600, 150) //期望模板广告view的size,单位dp
                .build();
        mTTAdNative.loadBannerExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            //请求失败回调
            @Override
            public void onError(int code, String message) {
                Log.d(TAG, "showBannerMiddle code==" + code + ", message = " + message);
            }

            //请求成功回调
            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                if (ads.get(0) == null) {
                    return;
                }
                final TTNativeExpressAd ad = ads.get(0);
                ad.setSlideIntervalTime(3 * 1000);
                ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
                    @Override
                    public void onAdClicked(View view, int i) {

                    }

                    @Override
                    public void onAdShow(View view, int i) {

                    }

                    @Override
                    public void onRenderFail(View view, String s, int i) {

                    }

                    @Override
                    public void onRenderSuccess(View view, float v, float v1) {
                        if (container != null) {
                            container.removeAllViews();
                            container.addView(view);
                        }
                    }
                });

                final DislikeInfo dislikeInfo = ad.getDislikeInfo();
                if (dislikeInfo != null && dislikeInfo.getFilterWords() != null && !dislikeInfo.getFilterWords().isEmpty()) {
                    final DislikeDialog dislikeDialog = new DislikeDialog(activity, dislikeInfo);
                    dislikeDialog.setOnDislikeItemClick(new DislikeDialog.OnDislikeItemClick() {
                        @Override
                        public void onItemClick(FilterWord filterWord) {
                            //用户选择不喜欢原因后，移除广告展示
                            container.removeAllViews();
                        }
                    });
                    dislikeDialog.setOnPersonalizationPromptClick(new DislikeDialog.OnPersonalizationPromptClick() {
                        @Override
                        public void onClick(PersonalizationPrompt personalizationPrompt) {

                        }
                    });
                    ad.setDislikeDialog(dislikeDialog);
                }

                ad.render();
            }
        });
    }

    public void loadExpressAd(ViewGroup mExpressContainer) {
        if (!AdConfig.isShowAd || AdConfig.adDisable || mExpressContainer == null) {
            return;
        }
        mExpressContainer.removeAllViews();
        float expressViewWidth = UIUtils.getScreenWidthDp(activity);
        float expressViewHeight = 0;//如果高度设置为0,则高度会自适应

        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(AdConfig.getFeedCodeId()) //广告位id
                .setAdCount(1) //请求广告数量为1到3条
                .setExpressViewAcceptedSize(expressViewWidth,expressViewHeight) //期望模板广告view的size,单位dp
                .build();
        //step5:请求广告，对请求回调的广告作渲染处理

        mTTAdNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int code, String message) {
                Log.d(TAG, "loadExpressAd code==" + code + ", message = " + message);
                mExpressContainer.removeAllViews();
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                if (ads == null || ads.size() == 0){
                    return;
                }

                TTNativeExpressAd mTTAd = ads.get(0);
                mTTAd.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
                    @Override
                    public void onAdClicked(View view, int type) {

                    }

                    @Override
                    public void onAdShow(View view, int type) {

                    }

                    @Override
                    public void onRenderFail(View view, String msg, int code) {

                    }

                    @Override
                    public void onRenderSuccess(View view, float width, float height) {
                        mExpressContainer.removeAllViews();
                        mExpressContainer.addView(view);
                    }
                });

                //使用自定义样式
                DislikeInfo dislikeInfo = mTTAd.getDislikeInfo();
                if (dislikeInfo == null || dislikeInfo.getFilterWords() == null || dislikeInfo.getFilterWords().isEmpty()) {
                    return;
                }
                final DislikeDialog dislikeDialog = new DislikeDialog(activity, dislikeInfo);
                dislikeDialog.setOnDislikeItemClick(new DislikeDialog.OnDislikeItemClick() {
                    @Override
                    public void onItemClick(FilterWord filterWord) {
                        //用户选择不喜欢原因后，移除广告展示
                        mExpressContainer.removeAllViews();
                    }
                });
                dislikeDialog.setOnPersonalizationPromptClick(new DislikeDialog.OnPersonalizationPromptClick() {
                    @Override
                    public void onClick(PersonalizationPrompt personalizationPrompt) {
                    }
                });
                mTTAd.setDislikeDialog(dislikeDialog);

                mTTAd.render();
            }
        });
    }
}